<?php
/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * @Date: 2022-03-10 15:50:55
 * @LastEditors: Sam
 * @LastEditTime: 2022-05-05 23:30:36
 */
namespace app\api\controller;
use app\__MODULE__\model\{User as UserModel,Sign as SignModel,SignLog};
use hg\apidoc\annotation as Apidoc;
use think\facade\Db;



/**
 * @Apidoc\Title("签到")
 */
class Sign extends ApiBase
{


    private $max_day = 7; //签到轮回 连续签到多久轮回
        /**
     * @Apidoc\Title("签到")
     * @Apidoc\Url("/api/sign_up")
     * @Apidoc\Method("POST")
     */
    public  function sign_up(){
        $uid = $this->get_user_id();
        if(SignModel::where('uid',$uid)->whereTime('last_sign','today')->count()) json_response(0,'今天已经签到过了');
        $sign  = SignModel::where('uid',$uid)->find();
        Db::startTrans();
        try {
            if($sign){
                //查询昨天有没有签到
                if(SignModel::where('uid',$uid)->whereTime('last_sign','yesterday')->count()){
                    //昨天已经签到过 连续签到
                    if($sign->sign_day == $this->max_day){
                        //签到满 重新轮回
                        $sign->sign_day = 1;
                    }else{
                        $sign->sign_day += 1; 
                    }
                }else{
                    //非连续签到 中断 重新轮回
                    $sign->sign_day = 1;
                }
                $sign->last_sign = time();
                $sign->save();
                
            }else{
                //没有签到过
              $res =   SignModel::create([
                    'uid' =>$uid,
                    'last_sign' => time(),
                    'sign_day' =>1
                ]);
            }
            SignLog::create([
                'uid' => $uid,
                'year' => date('Y'),
                'month' =>date('m'),
                'day'  => date('d')
            ]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
           show(0,$e->getMessage());
        }
        
        json_response(1,'签到成功');
    }

           /**
     * @Apidoc\Title("签到记录")
     * @Apidoc\Url("/api/sign_log")
     * @Apidoc\Method("GET")
     * @Apidoc\Param("page", type="int", desc="页码 默认1")
     * @Apidoc\Param("limit", type="int", desc="数据量 默认10")
     * @Apidoc\Returned("[]", type="list[]",
     *     @Apidoc\Returned("year", type="string",desc="年"), 
     *     @Apidoc\Returned("month", type="string",desc="月"), 
     *     @Apidoc\Returned("day", type="string",desc="日"), 
     *      @Apidoc\Returned("create_time", type="string",desc="具体时间"), 
     * )
     */
    public  function sign_log(){
        $uid  = $this->get_user_id();
        $page = request()->param('page/d',1);
        $limit = request()->param('limit/d',10);
        $list = SignLog::where('uid',$uid)->field('year,month,day,create_time')->page($page,$limit)->select();
        \json_response(1,'success',$list);
    }
}